import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: AliceMana
 * Date: 2023-01-01
 * Time: 15:59
 */

       /* 1. 给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
          2. 实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
          3. 其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
          4. 最终再汇总两个和, 进行相加
          5. 记录程序的执行时间.*/

public class Test1 {
    public static void main(String[] args) {
        long beg = System.currentTimeMillis();
        Random random = new Random();
        int[] arr = new int[1000_0000];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = random.nextInt(100)+1;
        }

        Add add = new Add();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < arr.length; i+=2) {
                add.addEve(arr[i]);
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 1; i < arr.length; i+=2) {
                add.addOdd(arr[i]);
            }
        });


        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println(add.result());

        long end = System.currentTimeMillis();

        System.out.println("用时 " + (end-beg) + " ms");
    }

    static class Add {
        public int evenNumbers;
        public int oddNumbers;

        public void addEve(int n) {
            evenNumbers += n;
        }

        public void addOdd(int n) {
            oddNumbers += n;
        }

        public int result() {
            return evenNumbers+oddNumbers;
        }
    }
}
